package com.yxch.admin.controller.user;

import com.yxch.admin.model.user.UserLoginDTO;
import com.yxch.admin.service.user.UserService;
import com.yxch.admin.utils.ImageCode;
import com.yxch.admin.utils.ResultAPI;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;


@Slf4j
@RestController
@RequestMapping("/yxch/admin")
public class LoginController {
    @Autowired
    UserService userService;

    @PostMapping("/login")
    public ResultAPI login(@RequestBody UserLoginDTO userLoginDTO, HttpSession session) throws ServletException, IOException {
        String imageCode = userLoginDTO.getImageCode();
        // 获取验证码
        String checkCode = (String) session.getAttribute(ImageCode.class.getName());

        // 这种情况一般都是直接访问login了
        if (imageCode.isEmpty()) {
            return ResultAPI.error("验证码不能为空！");
        }

        if (checkCode.isEmpty() || !checkCode.equalsIgnoreCase(imageCode)) {
            return ResultAPI.error("验证码错误！");
        }
        return userService.login(userLoginDTO);
    }

    @RequestMapping("/getImageCode")
    public void getImageCode(HttpServletRequest request, HttpServletResponse response) {
        try {
            log.info("getImageCode");
            new ImageCode().doGet(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
